package com.hrb.monkey.activity.zxing;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import com.hrb.monkey.R;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;

public class ZxingCustomActivity extends AppCompatActivity {

    public static boolean isOpen = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zxing_custom);
        // 执行扫描页面的初始化
        CaptureFragment captureFragment=new CaptureFragment();
        //设置二维码扫描的定制页面
        CodeUtils.setFragmentArgs(captureFragment,R.layout.zxing_custom_layout);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        //替换原来的扫描组件
        getSupportFragmentManager().beginTransaction().replace(R.id.capture_container, captureFragment).commit();
        initView();
    }

    private void initView() {
        //操作开关闪光灯
        LinearLayout linearLayout = findViewById(R.id.linear1);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isOpen) {
                    CodeUtils.isLightEnable(true);
                    isOpen = true;
                } else {
                    CodeUtils.isLightEnable(false);
                    isOpen = false;
                }

            }
        });
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
            bundle.putString(CodeUtils.RESULT_STRING, result);
            resultIntent.putExtras(bundle);
            ZxingCustomActivity.this.setResult(RESULT_OK, resultIntent);
            ZxingCustomActivity.this.finish();
        }

        @Override
        public void onAnalyzeFailed() {
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
            bundle.putString(CodeUtils.RESULT_STRING, "");
            resultIntent.putExtras(bundle);
            ZxingCustomActivity.this.setResult(RESULT_OK, resultIntent);
            ZxingCustomActivity.this.finish();
        }
    };
}
